<template>
  <basic-container>
    <!-- <avue-tabs :option="tabOption" @change="handleChange" v-model="selectTab"></avue-tabs> -->
    <ArrowLeftBold
      @click="router.back()"
      width="24"
      height="24"
      style="padding-top: 4px; cursor: pointer"
      v-if="routerQuery.groupFlowType"
      title="返回"
    />
    <el-tabs v-model="selectTab" class="demo-tabs" @tab-click="handleChange">
      <el-tab-pane
        :label="item.label"
        :name="item.prop"
        v-for="item in tabOption.column"
        :key="item.prop"
      ></el-tab-pane>
    </el-tabs>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model:page="page"
      @search-change="searchChange"
      @selection-change="selectionChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @row-del="rowDel"
      v-model:search="search"
    >
      <template #menu-left>
        <!-- <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="permission.crf_delete && !routerQuery.groupFlowType && selectTab == 2"
          @click="handleDelete"
          >删 除
        </el-button> -->
        <!-- <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          v-if="!routerQuery.groupFlowType"
          >导 出
        </el-button> -->
      </template>
      <template #menu="{ row, index }">
        <el-button
          text
          plain
          @click="handleMenu(0, row, index)"
          style="color: #00c0ef"
          v-if="!routerQuery.groupFlowType"
          >查 看
        </el-button>
        <el-button
          text
          plain
          @click="handleMenu(1, row, index)"
          style="color: #00a65a"
          v-if="!routerQuery.groupFlowType && selectTab == 2 && row.isPublic != '1'"
          >重命名
        </el-button>
        <el-button
          text
          plain
          @click="handleMenu(2, row, index)"
          style="color: #3c8dbc"
          v-if="!routerQuery.groupFlowType && selectTab == 2 && row.isPublic != '1'"
          >编 辑
        </el-button>
        <el-button
          text
          plain
          @click="handleMenu(3, row, index)"
          style="color: red"
          v-if="!routerQuery.groupFlowType && selectTab == 2 && row.isPublic != '1'"
          >删 除
        </el-button>
        <el-button
          text
          plain
          @click="handleMenu(4, row)"
          style="color: #f39c12"
          v-if="selectTab == 2 && !routerQuery.groupFlowType && row.isPublic != '1'"
          >公 开
        </el-button>
        <el-button
          text
          plain
          @click="handleMenu(5, row)"
          style="color: #00c0ef"
          v-if="routerQuery.groupFlowType"
          >选 择
        </el-button>
      </template>
      <template #name="{ row }">
        <span
          @click="handleMenu(6, row)"
          :style="!routerQuery.groupFlowType ? 'cursor: pointer;color: #72afd2' : ''"
          >{{ row.name }}</span
        >
      </template>
    </avue-crud>
    <el-dialog v-model="isGroupCrf" :title="groupCrfTitle + '-流程库'" width="800">
      <div class="flow-text-content" v-for="(item, index) in flowList" :key="index">
        <div class="lord-content">
          <Fold style="width: 16px; height: 16px; margin-right: 5px" />
          <span>{{ item.title }}</span>
        </div>
        <div class="seed-content" v-for="(v, i) in item.crfList" :key="i">
          <Document style="width: 16px; height: 16px; margin-right: 5px" />
          <span @click="handleCrf(v.crf)">{{ v.crfName }}</span>
        </div>
      </div>
    </el-dialog>
    <el-dialog v-model="isElectricityCaseDialog" title="添加备注" width="500">
      <div class="edit-dialog-content">
        <el-radio-group v-model="diagnoseRadio">
          <el-radio value="1" border>首次诊断</el-radio>
          <el-radio value="2" border>复 诊</el-radio>
          <el-radio value="3" border>医 嘱</el-radio>
          <el-radio value="4" border>检测报告</el-radio>
          <el-radio value="5" border>其 他</el-radio>
          <el-input
            v-if="diagnoseRadio === '5'"
            v-model="restInputValue"
            placeholder="请输入内容"
          ></el-input>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isElectricityCaseDialog = false">取 消</el-button>
          <el-button type="primary" @click="dialogSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </basic-container>
</template>
<script setup>
import { findObject } from '@smallwei/avue';
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  createWithProcesslibrary,
} from '@/api/processlibrary/processLibrary';
import { copyFromProcessLibrary, processLibraryTreeWithCrf } from '@/api/group/group';
import { ref, reactive, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import website from '@/config/website';
import 'nprogress/nprogress.css';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
const crud = ref(null);
const store = useStore();
const routerQuery = ref({});
routerQuery.value = route.query;
const backRoutesVal = computed(() => store.getters.backRoutesVal);
const tabOption = reactive({
  column: [
    {
      // icon: 'el-icon-info',
      label: '公开流程',
      prop: 1,
    },
    {
      label: '私有流程',
      prop: 2,
    },
  ],
});
const selectTab = ref(2);
let isGroupCrf = ref(false);
let groupCrfTitle = ref('');
let flowList = ref([]);
const handleChange = tab => {
  console.log(tab);
  selectTab.value = tab.props.name;
  onLoad(page.value);
};
const form = ref({});
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
const option = ref({
  height: 'auto',
  calcHeight: 30,
  tip: false,
  searchShow: true,
  searchMenuSpan: 18,
  searchMenuPosition: 'right',
  border: true,
  index: true,
  viewBtn: true,
  selection: true,
  dialogClickModal: false,
  align: 'center',
  indexWidth: 80,
  indexLabel: '编号',
  // menu: false,
  // addBtn: false,
  labelWidth: 145,
  menuWidth: 400,
  delBtn: false,
  editBtn: false,
  column: [
    {
      label: '流程名称',
      prop: 'name',
      type: 'input',
      filterable: true,
      overHidden: true,
      rules: [
        {
          required: true,
          message: '请输流程名称',
          trigger: 'blur',
        },
      ],
      search: true,
      slot: true,
    },
    {
      label: '是否共享',
      prop: 'isPublic',
      type: 'select',
      dicData: [
        {
          label: '否',
          value: '0',
        },
        {
          label: '是',
          value: '1',
        },
      ],
      filterable: true,
      overHidden: true,
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
    },
    {
      label: '创建人',
      prop: 'createUser',
      type: 'select',
      dicUrl: `/blade-system/user/all-user-list`,
      props: {
        label: 'realName',
        value: 'id',
      },
      filterable: true,
      overHidden: true,
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
    },
    {
      label: '创建时间',
      prop: 'createTime',
      type: 'input',
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
      display: false,
    },
  ],
});
const data = ref([]);
let clickMneuVal = ref({});

let isElectricityCaseDialog = ref(false);
let diagnoseRadio = ref('1');
let restInputValue = ref('');

// 操作栏按钮点击
/*
  type 0:查看按钮点击
  type 1:重命名按钮点击
  type 2:编辑按钮点击
  type 3:删除按钮点击
  type 4:公开按钮点击
  type 5:选择按钮点击
  type 6:CRF名称点击
*/
const handleMenu = (type, row = {}, index = null) => {
  clickMneuVal.value = {
    type: type,
    row: row,
  };
  const actions = {
    0: () => {
      // crud.value.rowView(row, index);
      router.push({
        path: '/trial/groupFlow',
        query: {
          isProcessLibrary: '2', //1新增，2查看
          processLibraryId: row.id,
        },
      });
    },
    1: () => {
      crud.value.rowEdit(row, index);
    },
    2: () => {
      ElMessageBox.confirm(
        '此处修改不会影响之前调用该流程库创建的分组流程！如想修改分组流程，请前往分组设置进行修改！是否继续编辑流程库？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        router.push({
          path: '/trial/groupFlow',
          query: {
            isProcessLibrary: '1', //1新增，2查看
            processLibraryId: row.id,
          },
        });
      });
    },
    3: () => {
      crud.value.rowDel(row, index);
    },
    4: () => {
      ElMessageBox.confirm('一旦公开，不可编辑、配置、删除，不可撤回，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          row.isPublic = '1';
          return add(row);
        })
        .then(() => {
          onLoad(page.value);
          ElMessage.success('操作成功!');
        });
    },
    5: () => {
      if (routerQuery.value.isCase == '777') {
        routerQuery.value.crfId = row.id;
        routerQuery.value.eleMedicalRecordName = row.name;
        isElectricityCaseDialog.value = true;
      } else {
        copyFromProcessLibrary(row.id, routerQuery.value.groupId).then(res => {
          ElMessage.success('操作成功!');
          router.back();
        });
      }
    },
    6: () => {
      if (routerQuery.value.groupFlowType) return;
      groupCrfTitle.value = row.name;
      isGroupCrf.value = true;
      if (row.id) {
        initProcessLibraryTreeWithCrf(row.id);
      }
    },
  };

  // 执行对应的操作
  if (actions[type]) actions[type]();
};

// 添加备注弹窗点击事件
const dialogSubmit = () => {
  let remarkArr = ['首次诊断', '复 诊', '医 嘱', '检测报告', restInputValue.value];
  let caseName = remarkArr[Number(diagnoseRadio.value) - 1];
  if (diagnoseRadio.value === '5' && !restInputValue.value) {
    ElMessage.warning('请填写其他内容！');
    return;
  }
  let form = {
    caseId: routerQuery.value.caseManagementId,
    processlibraryId: routerQuery.value.crfId,
    remark: caseName,
  };
  createWithProcesslibrary(form.caseId, form.processlibraryId, form.remark).then(res => {
    if (res.data.code === 200) {
      ElMessage.success('提交成功!');
      setTimeout(() => {
        router.push({
          path: '/casemanagement/tabs',
          query: {
            selectTab: '2',
            caseManagementId: routerQuery.value.caseManagementId,
          },
        });
      }, 1000);
    }
  });
};

const storeCrfFlowDialogForm = computed(() => store.state.common.crfFlowDialogForm);
onMounted(() => {
  selectTab.value = 2;
  initOptionBtn();
  onLoad(page.value);
});

const initOptionBtn = () => {
  option.value.addBtn = true;
  if (routerQuery.value.groupFlowType) {
    option.value.addBtn = false;
  }
};
const initProcessLibraryTreeWithCrf = async processLibraryId => {
  let res = await processLibraryTreeWithCrf(processLibraryId);
  flowList.value = res.data.data;
  console.log(flowList.value, res);
};

const permission = computed(() => store.getters.permission);
const userInfo = computed(() => store.getters.userInfo);
const validData = (value, defaultVal = false) => (value ? true : defaultVal);
const permissionList = computed(() => ({
  addBtn: validData(permission.value.processLibrary_add, false),
  viewBtn: validData(false),
  delBtn: validData(permission.value.processLibrary_delete, false),
  editBtn: validData(permission.value.processLibrary_edit, false),
}));

// ids 计算属性
const ids = computed(() => {
  return selectionList.value.map(ele => ele.id).join(',');
});
// 流程名称点击打开的弹窗中，crf名称点击，进入crf详情
const handleCrf = crfId => {
  store.commit('SET_CRFFLOW_DIALOG_FORM', clickMneuVal.value.row);
  router.push({
    path: '/scaleTemplate/formUse',
    query: { id: crfId },
  });
};
const rowSave = (row, done, loading) => {
  row.isPublic = '0';
  add(row)
    .then(res => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
      router.push({
        path: '/trial/groupFlow',
        query: {
          isProcessLibrary: '1', //1新增，2查看
          processLibraryId: res.data.data.id,
        },
      });
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowUpdate = (row, index, done, loading) => {
  update(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(ids.value);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleExport = () => {
  const downloadUrl = `/blade-processlibrary/processLibrary/export-processLibrary?${
    website.tokenHeader
  }=${getToken()}`;
  const { name } = query.value;
  let values = {
    name_: name,
  };

  ElMessageBox.confirm('是否导出数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    NProgress.start();
    exportBlob(downloadUrl, values).then(res => {
      downloadXls(res.data, `crf流程库${dateNow()}.xlsx`);
      NProgress.done();
    });
  });
};

const beforeOpen = (done, type) => {
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = res.data.data;
    });
  }
  done();
};

const searchReset = () => {
  query.value = {};
  onLoad(page.value);
};

const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  onLoad(page.value, params);
  done();
};

const selectionChange = list => {
  selectionList.value = list;
};

const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};

const currentChange = currentPage => {
  page.value.currentPage = currentPage;
  onLoad(page.value, query.value);
};

const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
  onLoad(page.value, query.value);
};

const refreshChange = () => {
  onLoad(page.value, query.value);
};

const onLoad = (page, params) => {
  loading.value = true;
  let values = {
    descs: 'create_time',
    ...params,
    isPublic: selectTab.value == 1 ? 1 : 0,
  };
  getList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    data.value = DATA.records;
    loading.value = false;
    selectionClear();
    // 判断当前vuex中的数据是否有值，有值的话就把crf名称点击的那个弹窗打开，并调用接口，此判断用于在点crf名称跳转到crf详情的时候，在返回，弹窗还是打开状态
    if (Object.keys(storeCrfFlowDialogForm.value).length != 0) {
      groupCrfTitle.value = storeCrfFlowDialogForm.value.name;
      isGroupCrf.value = true;
      if (storeCrfFlowDialogForm.value.id) {
        initProcessLibraryTreeWithCrf(storeCrfFlowDialogForm.value.id);
      }
      store.commit('SET_CRFFLOW_DIALOG_FORM', {});
    }
  });
};
</script>
<style scoped lang="scss">
.flow-text-content {
  width: 100%;
  height: auto;
  background-color: #2c3b41;
}
.lord-content {
  color: #fff;
  padding: 5px 10px;
  font-size: 14px;
  display: flex;
  align-items: center;
}
.seed-content {
  color: #afbdb4;
  padding: 5px 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
  cursor: pointer;
}
.edit-dialog-content {
  width: 100%;
  height: auto;
  min-height: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.edit-dialog-content {
  ::v-deep .el-radio-group {
    width: 170px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  ::v-deep .el-radio {
    margin-bottom: 10px;
  }
}
</style>
